package yunhe.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;

import yunhe.biz.CusBiz;
import yunhe.entity.Customer;
import yunhe.entity.Product;

@WebServlet(name="CusServlet",urlPatterns="/CustomerServlet")
public class CustomerServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		CusBiz cusBiz=new CusBiz();
		//当前页(字符串)
		String pageIndex=req.getParameter("pageIndex");
		if(pageIndex==null){
			pageIndex="1";
		}
		//当前页（转换int）
		int curPage=Integer.parseInt(pageIndex);
		//总条数
		int cusCount=cusBiz.getCusCount();
		//每页显示行数
		int pageSize=10;
		//页数
		int totalPages=cusCount%pageSize==0?cusCount/pageSize:cusCount/pageSize+1;
				
		if(curPage<1){
			curPage=1;
		}else if(curPage>totalPages){
			curPage=totalPages;
		}
		String search=req.getParameter("search");
		String searchText=req.getParameter("searchText");
		HashMap<String,String> searchMap=new HashMap<>();
		searchMap.put("search", search);
		searchMap.put("searchText", searchText);
		ArrayList<Customer> cusList=cusBiz.getAllCus(searchMap);		
		
		JSONArray jsonArray=new JSONArray();
		if(!cusList.isEmpty()){
	         for (int i=0;i<cusList.size();i++){
	             Map<String,String> mss=new HashMap<String,String>();
	             mss.put("cusId",cusList.get(i).getCusId());
	             mss.put("cusName",cusList.get(i).getCusName());
	             mss.put("cusEmail",cusList.get(i).getCusEmail());
	             mss.put("cusAddr",cusList.get(i).getCusAddr());
	             mss.put("cusTel",cusList.get(i).getCusTel());
	             mss.put("cusPhone",cusList.get(i).getCusPhone());
	             mss.put("cusFax",cusList.get(i).getCusFax());
	             mss.put("cusBank",cusList.get(i).getCusBank()+"");
	             mss.put("cusAccount",cusList.get(i).getCusAccount()+"");
	             mss.put("cusTaxNum",cusList.get(i).getCusTaxNum()+"");
	             mss.put("cusLinkName",cusList.get(i).getCusLinkName()+"");
	             jsonArray.put(mss);
	         }
	     }
		String str="{\"total\":"+cusCount+",\"rows\":"+jsonArray.toString()+"}";
		resp.getWriter().print(str);
		
//		req.setAttribute("cusList", cusList);
//		req.setAttribute("curPage", curPage);
//		req.setAttribute("totalPages", totalPages);
//		req.getRequestDispatcher("/FileMgr/CustomerFile.jsp").forward(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
}
